package com.nageoffer.shortlink.admin.web;

import cn.hutool.core.util.StrUtil;
import com.nageoffer.shortlink.common.dto.admin.biz.UserContext;
import com.nageoffer.shortlink.common.dto.admin.biz.UserInfoDTO;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;


@RequiredArgsConstructor
public class UserInfoInterceptor implements HandlerInterceptor {
    private final StringRedisTemplate stringRedisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        String path = request.getRequestURI();
//        String method = request.getMethod();
//        String token = request.getHeader("token");
//        String username = request.getHeader("username");
//        if ("/api/short-link/user".equals(path) && "POST".equalsIgnoreCase(method)) {
//            // 直接返回 true，表示放行，不处理
//            return true;
//        }
//        if (!StrUtil.isAllNotBlank(token,username)) {
//            //throw new ClientException(UserErrorCodeEnum.USER_TOKEN_FAIL);
//            return false;
//        }
//        Object userJsonStr;
//        try {
//            userJsonStr = stringRedisTemplate.opsForHash().get("login:" + username, token);
//            if (userJsonStr==null) {
//                //throw new ClientException(UserErrorCodeEnum.USER_TOKEN_FAIL);
//                return false;
//            }
//        } catch (Exception e) {
//            //throw new ClientException(UserErrorCodeEnum.USER_TOKEN_FAIL);
//            return false;
//        }
//        UserInfoDTO userInfoDTO = JSONUtil.toBean(userJsonStr.toString(), UserInfoDTO.class);
//        UserContext.setUser(userInfoDTO);
//        return true;
        String token = request.getHeader("token");
        String username = request.getHeader("username");
        if (!StrUtil.isAllNotBlank(token,username)) {
            return true;
        }
        String userId = request.getHeader("userId");
        String realName = request.getHeader("realName");
        UserInfoDTO userInfoDTO = UserInfoDTO.builder()
                .id(userId)
                .realName(realName)
                .token(token)
                .username(username)
                .build();
        UserContext.setUser(userInfoDTO);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserContext.removeUser();
    }
}
